package com.dp1.pucp.Seguridad.Vista;

import com.dp1.pucp.Modelo.Clases.Usuario;
import com.dp1.pucp.Seguridad.Controlador.MantPerfilControlador;
import com.dp1.pucp.Util.Validaciones;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class MantUsuarioGUI2 extends javax.swing.JInternalFrame {

    private JFrame padreVentana;
    private MantPerfilControlador perfilControlador;
    private JTable tblResultados;
    private DefaultTableModel modelo;
    private JScrollPane scroll;
    private Border empty;

    public MantUsuarioGUI2() {
        initComponents();
        this.setTitle("Mantenimiento de Usuarios");
        try {
            setFrameIcon(new ImageIcon(getClass().getClassLoader().getResource("Imagenes/hombre_icono.png")));
        } catch (Exception ex) {
        }
    }

    public JFrame getPadre() {
        return padreVentana;
    }

    public String getUsuario() {
        return txtUsuario.getText().trim();
    }

    public String getEmpleado() {
        return txtEmpleado.getText().trim();
    }

    public int getEstado() {
        return cmbEstado.getSelectedIndex();
    }

    public int getFilaSel() {
        return tblResultados.getSelectedRow();
    }

    public void addNuevoListener(ActionListener ml) {
        this.btnCrear.addActionListener(ml);
    }

    public void addEditarListener(ActionListener ml) {
        this.btnEditar.addActionListener(ml);
    }

    public void addBuscarListener(ActionListener ml) {
        this.btnBuscar.addActionListener(ml);
    }

    public void addLimpiarListener(ActionListener ml) {
        this.btnLimpiar.addActionListener(ml);
    }

    public void realizarFiltro(ArrayList<Usuario> lista) {
        ArrayList<Usuario> listUsuario = new ArrayList<>();
        ArrayList<Usuario> tempListUsuario;

        tempListUsuario = lista;
        if (this.getEstado() != 0) {
            for (int i = 0; i < tempListUsuario.size(); i++) {
                if (tempListUsuario.get(i).getEstado() == this.getEstado()) {
                    listUsuario.add(tempListUsuario.get(i));
                }
            }
        } else {
            listUsuario = tempListUsuario;
        }


        tempListUsuario = listUsuario;
        listUsuario = new ArrayList<>();

        if (!this.getUsuario().equalsIgnoreCase("")) {

            for (int i = 0; i < tempListUsuario.size(); i++) {
                if (tempListUsuario.get(i).getUsuario().toUpperCase().contains(this.getUsuario().toUpperCase())) {
                    listUsuario.add(tempListUsuario.get(i));
                }
            }
        } else {
            listUsuario = tempListUsuario;
        }

        tempListUsuario = listUsuario;
        listUsuario = new ArrayList<>();


        if (!this.getEmpleado().equalsIgnoreCase("")) {

            for (int i = 0; i < tempListUsuario.size(); i++) {
                if (tempListUsuario.get(i).getEmpleado().getNombre().toUpperCase().contains(this.getEmpleado().toUpperCase())) {
                    listUsuario.add(tempListUsuario.get(i));
                }
            }
        } else {
            listUsuario = tempListUsuario;
        }

        this.llenaGrilla(listUsuario);
    }

    public void llenaGrilla(ArrayList<Usuario> listUsuario) {
        panelTabla.removeAll();
        TitledBorder tituloResultado = BorderFactory.createTitledBorder(empty, "Resultado:");
        tituloResultado.setTitleJustification(TitledBorder.LEFT);
        panelTabla.setBorder(BorderFactory.createTitledBorder("Resultados"));
        panelTabla.updateUI();
        if (listUsuario != null) {
            if (!listUsuario.isEmpty()) {
                modelo = new DefaultTableModel() {
                    @Override
                    public boolean isCellEditable(int fila, int columna) {
                        return false;
                    }
                };

                modelo.setRowCount(listUsuario.size());
                Object nombreCols[] = new Object[7];
                nombreCols[0] = "";
                nombreCols[1] = "Usuario";
                nombreCols[2] = "Empleado";
                nombreCols[3] = "Perfil";
                nombreCols[4] = "Estado";
                nombreCols[5] = "Última Modificación";
                nombreCols[6] = "Último Ingreso";
                modelo.setColumnIdentifiers(nombreCols);


                for (int i = 0; i < listUsuario.size(); i++) {
                    modelo.setValueAt(i + 1, i, 0);
                    modelo.setValueAt(listUsuario.get(i).getUsuario(), i, 1);
                    modelo.setValueAt(listUsuario.get(i).getEmpleado().getNombre(), i, 2);
                    modelo.setValueAt(listUsuario.get(i).getPerfil().getNombre(), i, 3);
                    if (listUsuario.get(i).getEstado() == 1) {
                        modelo.setValueAt("ACTIVO", i, 4);
                    }
                    if (listUsuario.get(i).getEstado() == 2) {
                        modelo.setValueAt("INACTIVO", i, 4);
                    }
                    if (listUsuario.get(i).getEstado() == 3) {
                        modelo.setValueAt("BLOQUEADO", i, 4);
                    }
                    modelo.setValueAt(listUsuario.get(i).getUltimaModificacion(), i, 5);
                    modelo.setValueAt(listUsuario.get(i).getUltimaFechaIngreso(), i, 6);
                }


                tblResultados = new JTable();
                tblResultados.setDragEnabled(false);
                tblResultados.setModel(modelo);
                TableColumn tcol = tblResultados.getColumn("");
                tcol.setPreferredWidth(20);
                tcol.setMinWidth(20);
                tcol.setMaxWidth(20);
                tblResultados.getColumnModel().getColumn(0).setCellRenderer(tblResultados.getTableHeader().getDefaultRenderer());
                tblResultados.setEnabled(true);
                tblResultados.setRowSelectionAllowed(true);
                scroll = new JScrollPane(tblResultados);
                panelTabla.add(scroll);

            } else {
                Validaciones.mostrarMensajeAvisoVal("No se encontraron resultados.");
            }
        } else {
            Validaciones.mostrarMensajeAvisoVal("No se encontraron resultados.");
        }

        panelTabla.updateUI();
    }

    public void llenaComboEstado(ArrayList<String> lista) {
        if (lista != null) {
            for (String opc : lista) {
                cmbEstado.addItem(opc);
            }
        }
    }

    public void LimpiarDatos() {
        txtEmpleado.setText("");
        txtUsuario.setText("");
        cmbEstado.setSelectedIndex(0);
        panelTabla.removeAll();
        panelTabla.setBorder(empty);
        panelTabla.updateUI();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblUsuario = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        lblEmpleado = new javax.swing.JLabel();
        txtEmpleado = new javax.swing.JTextField();
        lblEstado = new javax.swing.JLabel();
        cmbEstado = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        panelTabla = new javax.swing.JPanel();
        btnEditar = new javax.swing.JButton();
        btnCrear = new javax.swing.JButton();

        setClosable(true);
        setMaximumSize(new java.awt.Dimension(645, 690));
        setMinimumSize(new java.awt.Dimension(645, 690));
        setPreferredSize(new java.awt.Dimension(645, 690));
        setVisible(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Buscar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Ubuntu", 0, 15))); // NOI18N
        jPanel1.setToolTipText("");

        lblUsuario.setText("Usuario:");

        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyTyped(evt);
            }
        });

        lblEmpleado.setText("Empleado:");

        txtEmpleado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtEmpleadoKeyTyped(evt);
            }
        });

        lblEstado.setText("Estado:");

        btnBuscar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/buscar.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.setBorderPainted(false);
        btnBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        btnLimpiar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/clear.png"))); // NOI18N
        btnLimpiar.setText("Limpiar");
        btnLimpiar.setBorderPainted(false);
        btnLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUsuario)
                            .addComponent(lblEstado)
                            .addComponent(lblEmpleado))
                        .addGap(74, 74, 74)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtUsuario)
                            .addComponent(txtEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(216, 216, 216)
                        .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnLimpiar)))
                .addContainerGap(167, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblUsuario)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblEmpleado)
                            .addComponent(txtEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7)
                        .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lblEstado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnLimpiar)))
        );

        panelTabla.setMaximumSize(new java.awt.Dimension(690, 645));
        panelTabla.setMinimumSize(new java.awt.Dimension(690, 645));
        panelTabla.setPreferredSize(new java.awt.Dimension(690, 645));
        panelTabla.setLayout(new java.awt.BorderLayout());

        btnEditar.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/edit1.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setBorderPainted(false);
        btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEditar.setMaximumSize(new java.awt.Dimension(60, 76));
        btnEditar.setMinimumSize(new java.awt.Dimension(60, 76));
        btnEditar.setPreferredSize(new java.awt.Dimension(60, 76));
        btnEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        btnCrear.setFont(new java.awt.Font("Ubuntu", 0, 10)); // NOI18N
        btnCrear.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/nuevo.png"))); // NOI18N
        btnCrear.setText("Agregar");
        btnCrear.setBorderPainted(false);
        btnCrear.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCrear.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(btnCrear, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(panelTabla, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCrear))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(panelTabla, javax.swing.GroupLayout.PREFERRED_SIZE, 308, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyTyped
        String car = txtUsuario.getText();
        if (car.length() >= 25) {
            evt.consume();
        }
        Validaciones.soloTexto(evt);
    }//GEN-LAST:event_txtUsuarioKeyTyped

    private void txtEmpleadoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEmpleadoKeyTyped
        String car = txtEmpleado.getText();
        if (car.length() >= 25) {
            evt.consume();
        }
        Validaciones.soloTexto(evt);
    }//GEN-LAST:event_txtEmpleadoKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCrear;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JComboBox cmbEstado;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblEmpleado;
    private javax.swing.JLabel lblEstado;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPanel panelTabla;
    private javax.swing.JTextField txtEmpleado;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
